<?php
/**
 *
 *
 *
 */
namespace Yz\modules\Captcha;

class Model_Captcha
    extends \Yz_Model_Abstract
    implements \Yz_Model_Interface
{

    const SESSION_VAR_NAME = "YZ_CAPTCHA";

    /**
     *  The description of model
     *
     */
    protected $code;


    /**
     *  @return string
     */
    public function getCode()
    {
        debug();
        return $this->code;
    }

    /**
     *  @return binary string
     */
    public function getImage()
    {
        debug();
        if (! function_exists("imagejpeg")) {
            throw \Yz_Exception_NotImplemented::_new(array('function' => 'imagejpeg'));
        }
        $o = "";
        $captSlave = new Model_kcaptcha_kcaptcha();
        $o = $captSlave->getImage();
        $this->setCode( $captSlave->getKeyString() );
        return $o;
    }

    /**
     *  @param string the code supplied by user
     *  @return bool match
     *  @throw Captcha_Exception
     *  @throw InvalidArgument
     *  @throw InvalidValueType
     */
    public function verifyCode( $code )
    {
        debug();
        $code = \Yz_String::testNotEmpty($code);
        $session = \Yz_Session_Default::getInstance();
        $savedCode = $session[self::SESSION_VAR_NAME];
        unset($session[self::SESSION_VAR_NAME]);
        if ($savedCode === strtolower($code)) {
            return true;
        }
        throw new Exception_CodeIsWrong;
    }

    /**
     *  @return string
     */
    public function getContentType()
    {
        return "image/jpeg";
    }

    /** save code to session
     *
     */
    protected function setCode( $code )
    {
        $this->code = $code;
        $session = \Yz_Session_Default::getInstance();
        $session[self::SESSION_VAR_NAME] = strtolower($code);
        return $this;
    }

    /**
     *  Empty init due to no items
     */
    protected function init()
    {
        return $this;
    }

} // class
